import AntModal from '@/components/pt/dialog/AntModal'
import AdvanceTable from '@/components/pt/table/AdvanceTable'
import BizPayableDetailForm from '@/views/biz/bizcustomerpayable/modules/BizPayableDetailForm.vue'
import {getNowFormatStr} from '@/utils/util';
import { addBizPayment, updateBizPayment } from '@/api/biz/bizPayment'
import { getBizCustomerDetailInfo,delBizCustomerAccountDetail,getBizPaymentDetail,addBizCustomerAccountDetail } from '@/api/biz/bizCustomerAccount'
import moment from 'moment';
export default {
  name: 'CreateForm',
  props: {
    payOptions: {
      type: Array,
      required: false
    }
  },
  components: {
    AntModal,
    AdvanceTable,
    BizPayableDetailForm
  },
  data () {
    return {
      open: false,
      closeDialog: true,
      spinning: false,
      delayTime: 100,
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      loading: false,
      disabled: false,
      total: 0,
      id: undefined,
      multiple:false,
      formTitle: '',
      detailList:[],
      selectedRowKeys:[],
      selectedAccountRowKeys:[],
      multipleAccount:false,
      showAddModal:false,
      queryType:1,
      orderList:[],
      columns: [
        {
          title: '销售单号',
          dataIndex:'orderNumber',
          align: 'center',
        },
        {
          title: '地址',
          dataIndex:'address',
          align: 'center'
        },
        {
          title: '日期',
          dataIndex:'orderDate',
          align: 'center'
        },
        {
          title: '金额',
          dataIndex:'totalAmount',
          align: 'center'
        },
        {
          title: '已结算额',
          dataIndex:'collectedAmount',
          align: 'center'
        },
        {
          title: '未结算额',
          align: 'center',
          scopedSlots: {
            customRender: 'nopaySlot'
          }
        },
        {
          title: '本次结算',
          dataIndex:'amount',
          align: 'center',
          scopedSlots: {
            customRender: 'curSlot'
          }
        }
      ],
      
      columns1: [
        {
          title: '收款账户',
          dataIndex:'payAccount',
          align: 'center',
          scopedSlots: {
            customRender: 'payAccount'
          }
        },
        {
          title: '收款金额',
          dataIndex:'payAmount',
          align: 'center',
          scopedSlots: {
            customRender: 'payAmount'
          }
        },
        {
          title: '备注',
          dataIndex:'remark',
          align: 'center',
          scopedSlots: {
            customRender: 'remark'
          }
        },
        {
          title: '操作',
          dataIndex:'operator',
          align: 'center',
          scopedSlots: {
            customRender: 'operator'
          }
        },
      ],
      // 表单参数
      form: {},
      rules: {
        customerId: [{ required: true, message: '客户不能为空', trigger: 'blur' }],

        orderType: [{ required: true, message: '订单类型不能为空', trigger: 'blur' }],
        payAmount: [{ required: true, message: '收款金额不能为空', trigger: 'blur' }],
        payDate: [{ required: true, message: '请选择收款日期', trigger: 'blur' }],
        payAccount: [{ required: true, message: '请选择收款账户', trigger: 'blur' }],
      }
    }
  },
  filters: {},
  created () {

  },
  computed: {},
  watch: {
  },
  mounted () {},
  methods: {
    getDetail(){
      let param = {
        accountCode:this.form.accountCode,
        type:this.queryType
      }
      getBizPaymentDetail(param).then(response => {
        this.form = response.data
        this.form.detailList = this.form.detailList.map(v=>(v.amount = +v.amount || 0,v))  
        this.countDetails()
      })
    },
    handleAllocation(){
      let total = this.orderList.filter(v=>v[this.columns1[0].dataIndex] !== '合计').reduce((pre,cur)=>{
        return this.$toDecimal(pre + +cur.payAmount)
      },0)
      let nopayTotal = this.form.detailList.filter(v=>v[this.columns[0].dataIndex] !== '合计').reduce((pre,cur)=>{
        return this.$toDecimal(pre + (this.$toDecimal(cur.totalAmount - +cur.collectedAmount)))
      },0)
      console.log('nopayTotal :>> ', nopayTotal);
      // 待付和应付总额相同，直接分配就可以了，不用判断
      if (nopayTotal === total) {
        this.form.detailList = this.form.detailList.map(v=>{
          let nopay = this.$toDecimal(+v.totalAmount - +v.collectedAmount)
          v.amount = nopay
          return v
        })
      }else{
        this.form.detailList = this.form.detailList.map(v=>{
          if (v[this.columns[0].dataIndex] === '合计') {
            let totalAmount = this.form.detailList.filter(v=>v[this.columns[0].dataIndex] !== '合计').reduce((pre,cur)=>{
              return this.$toDecimal(pre + +cur.amount)
            },0)
            v.amount = totalAmount
            return v
          }
          let nopay = this.$toDecimal(+v.totalAmount - +v.collectedAmount)
          if(+total >= +nopay && +nopay >0 ){
            v.amount = nopay
            total = this.$toDecimal(total - nopay)
          }else if(+total < +nopay && +total >=0){
            v.amount = total
            total = 0
          }else{
            v.amount = 0
          }
          return v
        })

      }
      this.amountChange()
    },
    onClose () {
      this.open = false
      this.reset()
      this.$emit('close')
    },
    // 取消按钮
    cancel () {
      this.open = false
      this.reset()
      this.$emit('close')
    },
    handleAdd(){
        if (!this.orderList.length || this.orderList[this.orderList.length - 1][this.columns1[0].dataIndex] !== '合计') {
          this.orderList.push({payAmount:0})
          let total = this.orderList.reduce((pre,cur)=>{
            return this.$toDecimal(+pre + +cur.payAmount) 
          },0)
          this.orderList.push({
            payAccount:'合计',
            payAmount:total
          })
        }else{
          this.orderList.splice(this.orderList.length - 1,0,{payAmount:0})
          this.countTotal()
        }
    },
    handleAddItem(){
      this.showAddModal = true
      this.$nextTick(()=>{
        this.$refs.bizPayableDetailForm.handleSelectDetail(this.form)
      })
    },
    selectOk(rows){
      let params = {
        accountCode:this.form.accountCode,
        payableDetails:rows
      }
      addBizCustomerAccountDetail(params).then(res=>{
        if(res.code == 200) {
          this.$message.success('操作成功')
           this.getDetail()
           this.$emit('ok')
         }else{
           this.$message.error(res.msg)
         }
      }).catch((err)=>{
           console.log('err >>',err) 
      })
    },
    countTotal(){
      // 修改合计
      let index = this.orderList.findIndex(v=>v.payAccount === '合计')
      if (index > -1) {
        let total = this.orderList.filter(v=>v.payAccount != '合计').reduce((pre,cur)=>{
          return this.$toDecimal(+pre + +cur.payAmount) 
        },0)
        let item = this.orderList[index]
        item.payAmount = total
        this.orderList.splice(index,1,item)
      }
    },
    // 计算合计
    countDetails(){
      if (!this.form.detailList.length || this.form.detailList[this.form.detailList.length - 1][this.columns[0].dataIndex] !== '合计') {
        let totalAmount = this.form.detailList.reduce((pre,cur)=>{
          return this.$toDecimal(+pre + +cur.totalAmount) 
        },0)
        let collectedAmount = this.form.detailList.reduce((pre,cur)=>{
          return this.$toDecimal(+pre + +cur.collectedAmount) 
        },0)
        let amount = this.form.detailList.reduce((pre,cur)=>{
          return this.$toDecimal(+pre + +cur.amount) 
        },0)
        console.log('amount :>> ', amount);
        this.form.detailList.push({
          orderNumber:'合计',
          totalAmount:totalAmount,
          collectedAmount:collectedAmount,
          amount:amount
        })
      }
    },
    /**
     * 禁用table选择框
     * @param {obj} record 
     */
     getCheckboxProps(record) {
      return { props: { disabled: record[this.columns1[0].dataIndex] === '合计' } }
    },
    /**
     * 禁用table选择框
     * @param {obj} record 
     */
     getDetailProps(record) {
      return { props: { disabled: record[this.columns[0].dataIndex] === '合计' } }
    },
    /**
     * @汇总收款金额
     */
    amountChange(){
      let total = this.form.detailList.filter(v=>v[this.columns[0].dataIndex] !== '合计').reduce((pre,cur)=>{
        return this.$toDecimal(pre + +cur.amount)
      },0)
      this.$set(this.form,'payAmount',total)
      this.countTotal()
    },
    // 表单重置
    reset () {
      this.form = {
        id: undefined,

        payCode: undefined,

        supplierCode: undefined,

        supplierName: undefined,

        payAmount: undefined,

        purchaseDate: undefined,

        hasAmount: undefined,

        remark: undefined,

        payDate: undefined,

        payAccount: undefined

      }
    },
    handlePayment (row,type) {
      this.reset()
      this.open = true
      this.form = JSON.parse(JSON.stringify(row))
      this.queryType = type
      this.$set(this.form,'payDate',moment(new Date()).format('YYYY-MM-DD'))
      if(this.form.accountCode){
        this.formTitle = '编辑收款单';
        this.getDetail()
      }else{
        this.formTitle = '新增收款单';
      }
    },
    /** 提交按钮 */
    submitForm: function (closeDialog) {
      this.closeDialog = closeDialog
      this.disabled = true
      this.$refs.form.validate(valid => {
        if (valid) {
          this.form.payableDetails = this.form.detailList.filter(v=>v[this.columns[0].dataIndex] !== '合计').map((val,index)=>(val.sort = index,val))
          delete this.form.id
          this.form.paymentDetailList = this.orderList.filter(v=>v.payAccount !== '合计')
          let total = this.orderList.filter(v=>v[this.columns1[0].dataIndex] !== '合计').reduce((pre,cur)=>{
            return pre + +cur.payAmount
          },0).toFixed(2)
          if(total != this.form.payAmount){
            this.$message.error('账户列表金额总计与明细总计不相等')
            this.disabled = false
            return
          }
          this.form.status = '0'
          const saveForm = JSON.parse(JSON.stringify(this.form))
          addBizPayment(saveForm).then(response => {
            this.$message.success('操作成功', 3)
              this.$emit('ok')
              this.open = false
              this.$emit('ok')
              this.$emit('close')
              this.disabled = false
          })
        } else {
          this.disabled = false
          return false
        }
      })
    },
    back () {
      const index = '/biz/bizpayable/index'
      this.$router.push(index)
    },
    
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.multiple = selectedRowKeys.length
    },
    onAccountSelectChange(selectedRowKeys, selectedRows) {
      this.selectedAccountRowKeys = selectedRowKeys
      this.multipleAccount = selectedRowKeys.length
    },
    handleDelete(){
      if (!this.selectedAccountRowKeys.length) {
        this.$message.error(
          '请选择要删除的数据',
          3
        )
        return
      }
      this.$confirm({
        title: '确认删除所选中数据?',
        onOk: () => {
          this.orderList = this.orderList.filter((v, index) => !this.selectedAccountRowKeys.includes(index) && !this.selectedAccountRowKeys.includes(v.id))
          this.selectedAccountRowKeys = []
          this.multipleAccount = false
          this.$message.success(
            '删除成功',
            3
          )
        }
      })
    },
    handleDeleteRows() {
      if (!this.selectedRowKeys.length) {
        this.$message.error(
          '请选择要删除的数据',
          3
        )
        return
      }
      this.$confirm({
        title: '确认删除所选中数据?',
        onOk: () => {
          // this.form.detailList = this.form.detailList.filter((v, index) => !this.selectedRowKeys.includes(index) && !this.selectedRowKeys.includes(v.id))
          // this.selectedRowKeys = []
          // this.multiple = false
          // this.$message.success(
          //   '删除成功',
          //   3
          // )
          delBizCustomerAccountDetail(this.selectedRowKeys.join(',')).then(res=>{
            if(res.code == 200) {
                this.$message.success(
                  '删除成功',
                  3
                )
                this.getDetail()
                this.$emit('ok')
            }else{
              this.message.error(res.msg)
            }
          })
        }
      })
    },

  }
}
